import jsList from "../js";
import Mixin from "@/config/mixins/smp-state";

import {
  setSessionItem,
  getSessionItem,
  // removeSessionItem
} from "@/basa/utils";
import {
  listSettlementPage,
  removeSettlement,
  revokeSettlement,
  sendBackSupplierSettlement
} from "../api/transportation-approval";

export default {
  mixins: [Mixin],
  data() {
    return {
      getReturnParams: {},
      jsList,
      isActive: 0,
      formData: {
        contractName: "",
        partyBName: ""
      },
      draggFlag: true,
      tableName: this.tableList.transportationMaintenanceApproval, // 表格命名
      // 动态表格
      tableTheadOptions: [],
      // 表格数据相关处理
      formatterList: {
        contractStateHandler({ paymentState }) {
          const temp = jsList.paymentState;
          return temp[temp.map(n => n.value).indexOf(paymentState)].label;
        }
      },
      // 全选以及页码
      totalNum: 0,
      total: 0,
      pageNoCode: 1,
      pageSizeCode: 10,
      formDataSearch: {},
      localSearchData: {},
      tableData: [],
      // 表格顶部按钮
      tableTopBtn: [
        { label: "全部", value: "0" },
        { label: "待提交", value: "1" },
        { label: "审批中", value: "2" },
        // { label: "已撤回", value: "3" },
        // { label: "审批不通过", value: "6" },
        { label: "审批退回", value: "3" }
      ],
      paymentState: "1",

      focuses: [
        { focus: "all" },
        { focus: "unsubmitted" },
        { focus: "approval" },
        { focus: "return" }
      ]
    };
  },
  created() {
    this.init();
  },
  methods: {
    // 失焦  去前后空格
    handleTrim(key) {
      if (!this.settlementForm[key] || this.settlementForm[key] == "") return;
      this.$set(
        this.settlementForm,
        key,
        this.settlementForm[key].replace(/(^\s*)|(\s*)$/g, "")
      );
    },
    init() {
      this.setTableWidth();
      this.renderTable();
    },
    // 退回操作
    openReturnDialog(row) {
      this.$refs['returnDialog'].visibleDialog = true
      this.getReturnParams.id = +row.id;
      this.getReturnParams.isShowPageLoading = true;
    },
    // 退回调用接口
    getValue(val) {
      this.getReturnParams.supplierSendBackReason = val;
      sendBackSupplierSettlement(this.getReturnParams).then(res => {
        this.$message({
          type: "success",
          message: res.data.message
        });
        this.getList();
      });

    },
    // 列表数据请求
    getList(reqObj) {
      let obj = {};
      obj = typeof reqObj == "object" ? reqObj : obj;
      obj.pageNo = this.pageNoCode;
      obj.pageSize = this.pageSizeCode;
      obj.paymentState = this.paymentState;
      obj.settlementStart = obj.paymentApplyDate ? obj.paymentApplyDate[0] : "";
      obj.settlementEnd = obj.paymentApplyDate ? obj.paymentApplyDate[1] : "";
      obj.isShowPageLoading = true;
      // console.log(this.isActive)
      if (this.isActive == 1) {
        obj.settlementStatus = "2,4";
      } else if (this.isActive == 2) {
        obj.settlementStatus = 3;
      } else if (this.isActive == 3) {
        obj.settlementStatus = 6;
      } else {
        obj.settlementStatus = null;
      }

      listSettlementPage(obj).then(res => {
        this.tableData = res.data.data.rows;
        this.totalNum = res.data.data.recordsTotal;
        this.tableData.forEach(item => {
          item.statusCode = item.settlementStatus;
          item.currSetCount = item.currSetCount ? Number(item.currSetCount).toFixed(3) : ''; //结算数量保留3位小数
          item.currSetMoney = item.currSetMoney ? Number(item.currSetMoney).toFixed(2) : "";

          if (item.settlementStatus == "2") {
            item.settlementStatus = "待提交";
          } else if (item.settlementStatus == "3") {
            item.settlementStatus = "审批中";
          } else if (item.settlementStatus == "4") {
            item.settlementStatus = "已撤回";
          } else if (item.settlementStatus == "5" && item.writeoffStatus == '2') {
            item.settlementStatus = "已冲销";
          } else if (item.settlementStatus == "5" && item.writeoffStatus == '1') {
            item.settlementStatus = "冲销中";
          } else if (item.settlementStatus == "5") {
            item.settlementStatus = "审批通过";
          } else if (item.settlementStatus == "6") {
            item.settlementStatus = "审批退回";
          } else if (item.settlementStatus == "7") {
            item.settlementStatus = "审批不通过";
          } else if (item.settlementStatus == "9") {
            item.settlementStatus = "已生效";
          } else if (item.settlementStatus == "11") {
            item.settlementStatus = "已删除";
          } else if (item.settlementStatus == "21") {
            item.settlementStatus = "冲销中";
          } else if (item.settlementStatus == "22") {
            item.settlementStatus = "已冲销";
          }
        });
      });
    },

    // 新增
    handleGoNew() {
      this.$router.push(
        "/settlement-management/transportation-maintenance-approval/transportation-add"
      );
    },

    // 详情
    goDetail(row) {
      // console.log(row.statusCode)
      if (row.statusCode == "2") {
        this.$router.push(
          `/settlement-management/transportation-maintenance-approval/transportation-check/${row.id}/0`
        );
      } else {
        this.$router.push(
          `/settlement-management/transportation-maintenance-approval/transportation-check-approval/${row.id}`
        );
      }
    },

    // 编辑
    goEdit(row) {
      this.$router.push(
        `/settlement-management/transportation-maintenance-approval/transportation-edit/${row.id}`
        // "/settlement-management/settlement-maintenance-approval/settlement-add"
      );
    },

    // 删除
    handleDelete(row) {
      this.$confirm("您确定要删除吗？", "删除确认", {
        distinguishCancelAndClose: true,
        confirmButtonText: "删除",
        cancelButtonText: "取消",
        customClass: "ccui-message-box-custom"
      })
        .then(() => {
          removeSettlement({
            id: row.id,
            isShowLoading: true,
            loadingMessage: "删除中,请稍等..."
          }).then(res => {
            let { code, message } = res.data;
            if (code === "0") {
              this.$message.success(message);
              this.getList();
            }
          });
        })
        .catch(() => { });
    },

    // 撤回
    getRevoke(row) {
      this.$confirm("确定要撤销吗?", "提示信息", {
        distinguishCancelAndClose: true,
        cancelButtonClass: "取消",
        confirmButtonText: "确定",
        customClass: "ccui-message-box-custom"
      })
        .then(() => {
          revokeSettlement({ id: row.id }).then(res => {
            let { code, message } = res.data;
            if (code === "0") {
              this.$message.success(message);
              this.getList();
              // this.$router.push(
              //   "/transportation-settlement/transportation-maintenance-approval/transportation-maintenance-unsubmitted"
              // );
            }
          });
        })
        .catch(() => { });
    },

    // 根据返回状态显示不同的文字颜色
    cellStyle({ row, column, rowIndex, columnIndex }) {
      // if (!["2", "6"].includes(row.paymentState)) return;
      // if (["contractName"].includes(column.property)) {
      //   return { color: "#0089EF", cursor: "pointer" };
      // }
    },

    // 行点击事件
    handleRowClick(row, column, event) {
      if (column.label == "结算单编号") {
        this.goDetail(row);
      }
    },
    addClass({ row, column, rowIndex, columnIndex }) {
      if (columnIndex === 1) {
        return "resAndSug";
      }
    },
    tabChange(data) {
      this.$router.push({ name: `transportation-maintenance-${data}` });
    },

    // 默认渲染表格
    renderTable() {
      const localTableData = localStorage.getItem(this.tableName)
        ? JSON.parse(localStorage.getItem(this.tableName))
        : [];
      let unfixedTableThead = this.jsList.unfixedTableThead.concat(
        this.jsList.fixedTableThead
      );
      let localTableDataStr = localTableData.map(
        ({ label, prop, formatter, align }) =>
          JSON.stringify({ label, prop, formatter, align })
      );
      let unfixedTableTheadStr = unfixedTableThead.map(
        ({ label, prop, width, formatter, align }) =>
          JSON.stringify({ label, prop, formatter, align })
      );

      if (localTableData.length === unfixedTableThead.length) {
        let flag = localTableDataStr.every(item =>
          unfixedTableTheadStr.includes(item)
        );
        if (flag) {
          // 完全相同
          this.tableTheadOptions = localTableData;
          this.tableThead = localTableData;
          this.jsList.unfixedTableThead = localTableData.filter(item => {
            return !this.jsList.fixedTableThead.find(
              cItem => item.prop === cItem.prop
            );
          });
        } else {
          // 长度相同但值不同
          this.tableThead = this.jsList.unfixedTableThead.concat(
            this.jsList.fixedTableThead
          );
          const comment = JSON.stringify(this.tableThead);
          localStorage.setItem(this.tableName, comment);
          const localTableData = JSON.parse(
            localStorage.getItem(this.tableName)
          );
          this.tableTheadOptions = localTableData;
        }
      } else {
        // 长度不同
        this.tableThead = this.jsList.unfixedTableThead.concat(
          this.jsList.fixedTableThead
        );
        const comment = JSON.stringify(this.tableThead);
        localStorage.setItem(this.tableName, comment);
        const localTableData = JSON.parse(localStorage.getItem(this.tableName));
        this.tableTheadOptions = localTableData;
      }
    },
    // 渲染本地存储表格宽度
    setTableWidth() {
      const localTableData = JSON.parse(localStorage.getItem(this.tableName));
      if (localTableData) {
        for (let i = 0; i < this.tableTheadOptions.length; i++) {
          if (this.tableTheadOptions[i].label === localTableData[i].label) {
            this.tableTheadOptions[i].width = localTableData[i].width;
          }
        }
      }
    },
    // 表格宽度更改存入
    tableTitleWidth(newWidth, oldWidth, column, event) {
      for (let i = 0; i < this.jsList.unfixedTableThead.length; i++) {
        if (this.jsList.unfixedTableThead[i].label === column.label) {
          this.jsList.unfixedTableThead[i].width = newWidth;
        }
      }
      this.tableThead = this.jsList.unfixedTableThead.concat(
        this.jsList.fixedTableThead
      );
      const comment = JSON.stringify(this.tableThead);
      localStorage.setItem(this.tableName, comment);
      this.tableTheadOptions = JSON.parse(localStorage.getItem(this.tableName));
      this.draggFlag = false;
      this.$nextTick(() => {
        this.draggFlag = true;
      });
    },
    // 上一页
    handlePrev() {
      --this.pageNoCode;
      this.getList();
    },
    // 下一页
    handleNext() {
      ++this.pageNoCode;
      this.getList();
    },
    // Todo 高级搜索所需函数 start
    search(searchData) {
      this.pageNoCode = 1;
      this.formDataSearch = JSON.parse(JSON.stringify(searchData));
      this.localSearchData = JSON.parse(JSON.stringify(searchData));
      setSessionItem("pageNo", this.tableName, {
        pageNo: this.pageNoCode,
        searchForm: this.localSearchData
      });
      this.getList(this.formDataSearch);
    },
    change(index, key, value) {
      const formDataKeys = Object.keys(this.formData);
      formDataKeys.map(_ => {
        if (_ !== key) this.formData[_] = "";
      });
    },
    // 每页条数发生改变
    handleSizeChange(val) {
      this.pageNoCode = 1;
      if (val !== "none") {
        this.pageSizeCode = val;
        setSessionItem("pageSize", this.tableName, val);
      }
      this.getList(this.formDataSearch);
    },
    // 当前页发生改变
    handleCurrentChange(val) {
      let searchFormData = getSessionItem("pageNo", this.tableName) || {};
      setSessionItem("pageNo", this.tableName, {
        pageNo: val,
        searchForm: searchFormData.searchForm || {}
      });
      this.formDataSearch = {
        ...this.formDataSearch,
        ...searchFormData.searchForm
      };
      // 跳转翻页都会调这个方法
      this.pageNoCode = val;
      this.getList(this.formDataSearch);
    }
  },
  // beforeRouteLeave(to, from, next) {
  //   removeSessionItem("pageNo");
  //   for (var key in this.$vnode.parent.parent.componentInstance.cache) {
  //     delete this.$vnode.parent.parent.componentInstance.cache[
  //       ishasAgentId(to.path, key)
  //     ];
  //   }
  //   next();
  // },
  activated() {
    this.$refs.search.resetForm();
    this.search(this.formData);
    if (Object.keys(this.localSearchData).length > 0) {
      setSessionItem("pageNo", this.tableName, {
        pageNo: this.pageNoCode,
        searchForm: this.localSearchData
      });
    }
    let localData = getSessionItem("pageNo", this.tableList.subConOptionList);
    let data = localData && localData.searchForm;
    this.getList({ ...this.formDataSearch, ...data });
  }
};
